package GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.border.EmptyBorder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.xml.transform.TransformerException;

import Xuly.MyColumn;
import Xuly.MyDatabase;
import Xuly.MyTable;

import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;
import javax.swing.JScrollPane;
import java.awt.Frame;

public class MainFrame extends JFrame {

	private JPanel contentPane;
	private static JTree jTreeDatabase;
	private static ArrayList<MyDatabase> listDatabase = new ArrayList<MyDatabase>();
	private String iTable = "";
	private String iDatabase = "";
	private String iColumn = "";
	private String iValue = "";
	private String iType = "";
	private Point point;
	private Point childLocal;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {

			public void run() {
				try {
					MainFrame frame = new MainFrame();
					frame.setVisible(true);
					LoadData("data");
					LoadTreeView();

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MainFrame() {

		setTitle("SQL server");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(200, 100, 694, 533);
		point = getLocation();
		childLocal = new Point(point.x + 200, point.y + 100);

		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		JMenu mnFile = new JMenu("File");
		menuBar.add(mnFile);

		JMenuItem mntmExit = new JMenuItem("Exit");
		mntmExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(1);
			}
		});
		mnFile.add(mntmExit);

		JMenu mnHelp = new JMenu("Help");
		menuBar.add(mnHelp);

		JMenuItem mntmAbout = new JMenuItem("About");
		mntmAbout.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				AboutDialog aboutDialog = new AboutDialog(childLocal);
				aboutDialog.setVisible(true);
			}
		});
		mnHelp.add(mntmAbout);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));

		final JLabel lableShow = new JLabel("lableShow");

		JSplitPane splitPane = new JSplitPane();
		contentPane.add(splitPane);

		JScrollPane scrollPane = new JScrollPane();
		splitPane.setLeftComponent(scrollPane);

		jTreeDatabase = new JTree();
		scrollPane.setViewportView(jTreeDatabase);
		jTreeDatabase.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				// System.out.print("sahfjsbaofg");

				TreePath rs = jTreeDatabase.getPathForLocation(e.getX(),
						e.getY());
				if (rs != null) {
					String str = rs.toString();
					// int index = str.lastIndexOf(",");
					switch (count(str, ',')) {
					case 0:
						iDatabase = "";
						iTable = "";
						iColumn = "";
						iValue = "";
						iType = "";
						break;
					case 1:
						iDatabase = str.substring(index(str, ',', 1) + 2,
								str.length() - 1);
						iTable = "";
						iColumn = "";
						iValue = "";
						iType = "";
						break;
					case 2:
						iDatabase = str.substring(index(str, ',', 1) + 2,
								index(str, ',', 2));
						iTable = str.substring(index(str, ',', 2) + 2,
								str.length() - 1);
						iColumn = "";
						iValue = "";
						iType = "";
						break;
					case 3:
						iDatabase = str.substring(index(str, ',', 1) + 2,
								index(str, ',', 2));
						iTable = str.substring(index(str, ',', 2) + 2,
								index(str, ',', 3));
						iColumn = str.substring(index(str, ',', 3) + 2,
								str.length() - 1);
						iValue = "";
						iType = "";
						break;
					case 4:
						iDatabase = str.substring(index(str, ',', 1) + 2,
								index(str, ',', 2));
						iTable = str.substring(index(str, ',', 2) + 2,
								index(str, ',', 3));
						iColumn = str.substring(index(str, ',', 3) + 2,
								index(str, ',', 4));

						if (str.contains("value: ")) {
							iValue = str.substring(index(str, ',', 4) + 2,
									str.length() - 1);
							iType = "";
						} else {
							iValue = "";
							iType = str.substring(index(str, ',', 4) + 2,
									str.length() - 1);
						}
						break;
					}

					CapNhapTile();

					lableShow.setText(" data: '" + iDatabase + "'\t table: '"
							+ iTable + "' \t column: '" + iColumn + "'\t"
							+ " value: '" + iValue + "' type: '" + iType
							+ "'  " + str);
				}

			}

		});
		jTreeDatabase.setBackground(Color.WHITE);
		jTreeDatabase.setModel(new DefaultTreeModel(new DefaultMutableTreeNode(
				"database") {
			{
			}
		}));

		splitPane.setRightComponent(lableShow);
		splitPane.setDividerLocation(200);

		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.NORTH);
		panel.setLayout(new FormLayout(
				new ColumnSpec[] { ColumnSpec.decode("max(31dlu;default)"),
						FormFactory.RELATED_GAP_COLSPEC,
						ColumnSpec.decode("113px"),
						FormFactory.RELATED_GAP_COLSPEC,
						ColumnSpec.decode("5dlu"),
						FormFactory.RELATED_GAP_COLSPEC,
						ColumnSpec.decode("max(73dlu;default)"),
						FormFactory.RELATED_GAP_COLSPEC,
						ColumnSpec.decode("max(9dlu;default)"),
						FormFactory.RELATED_GAP_COLSPEC,
						FormFactory.DEFAULT_COLSPEC,
						FormFactory.RELATED_GAP_COLSPEC,
						FormFactory.DEFAULT_COLSPEC,
						FormFactory.RELATED_GAP_COLSPEC,
						FormFactory.DEFAULT_COLSPEC,
						FormFactory.RELATED_GAP_COLSPEC,
						FormFactory.DEFAULT_COLSPEC, }, new RowSpec[] { RowSpec
						.decode("23px"), }));

		JButton btnCreateDatabase = new JButton("Create database");
		btnCreateDatabase.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String databaseName;
				databaseName = JOptionPane
						.showInputDialog("Nhập tên database: ");

				if (databaseName == null)
					return;

				while (ktTrungDatabase(databaseName) || databaseName.equals("")
						|| databaseName.contains(",")
						|| databaseName.contains(" ") || ktLaSo(databaseName) ) {

					if (ktTrungDatabase(databaseName))
						databaseName = JOptionPane
								.showInputDialog("Tên bị trùng - nhập lại: ");
					else if (databaseName.equals(""))
						databaseName = JOptionPane
								.showInputDialog("Chuỗi trắng - nhập lại: ");
					else if (databaseName.contains(","))
						databaseName = JOptionPane
								.showInputDialog("Chuỗi chứa ',' - nhập lại: ");
					else if (databaseName.contains(" "))
						databaseName = JOptionPane
								.showInputDialog("Chuỗi chứa khoảng trắng - nhập lại: ");
					else if (ktLaSo(databaseName))
						databaseName = JOptionPane
								.showInputDialog("Chuỗi chứa kí tự số - nhập lại: ");
					if (databaseName == null)
						return;
				}

				iDatabase = databaseName;
				CapNhapTile();
				MyDatabase newDatabase = new MyDatabase();
				newDatabase.setName(databaseName);

				try {
					newDatabase.WriteDatabaseToFile("data/" + databaseName
							+ ".xml");
				} catch (TransformerException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				listDatabase.add(newDatabase);
				try {
					LoadTreeView();
				} catch (TransformerException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			}
		});
		btnCreateDatabase.setSize(new Dimension(50, 25));
		panel.add(btnCreateDatabase, "3, 1");

		JButton btnCreateTable = new JButton("Create table");
		btnCreateTable.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				point = getLocation();

				if (iDatabase.equals("")) {
					MessageDialog messageDialog = new MessageDialog(
							"Chọn database!", childLocal);
					messageDialog.setVisible(true);
					return;
				}

				for (int i = 0; i < listDatabase.size(); i++)
					if (listDatabase.get(i).getName().equals(iDatabase)) {
						
						CreateTableDialog createTableDialog = new CreateTableDialog(
								listDatabase.get(i), childLocal);
						createTableDialog.setVisible(true);
						// Lay table tra ve
						MyTable table = createTableDialog.myTable;

						if (table != null) {
							listDatabase.get(i).getTables().add(table);

							// Load lai tree view
							try {
								LoadTreeView();
							} catch (TransformerException e2) {
								// TODO Auto-generated catch block
								e2.printStackTrace();
							}

							File f = new File("data/" + iDatabase + ".xml");

							// Xoa file database cu.
							try {
								f.delete();
							} catch (Exception e2) {
							}

							// Luu database moi cap nhat xuong file.
							try {
								listDatabase.get(i).WriteDatabaseToFile(
										"data/" + iDatabase + ".xml");
							} catch (TransformerException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						}
					}
			}
		});
		panel.add(btnCreateTable, "7, 1");

		JButton btnDeleleDatabase = new JButton("Delele Database ");
		btnDeleleDatabase.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				if (iDatabase.equals("")) {
					MessageDialog messageDialog = new MessageDialog(
							"Chọn database!", childLocal);
					messageDialog.setVisible(true);
					return;
				}

				ConfirmDialog confirmDialog = new ConfirmDialog(
						"Bạn có chắc muốn xóa database " + iDatabase + "?",
						childLocal);
				confirmDialog.setVisible(true);

				// Lay ket qua xac nhan co muon xoa hay khong.
				Boolean confirm = confirmDialog.result;
				// Neu khong muon xoa thi khong lam gi
				if (confirm == false)
					return;

				File f1 = new File("data/" + iDatabase + ".xml");
				boolean success = f1.delete();
				if (success) {
					for (int i = 0; i < listDatabase.size(); i++)
						if (listDatabase.get(i).getName().equals(iDatabase)) {
							listDatabase.remove(i);
						}

					try {
						LoadTreeView();
					} catch (TransformerException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

					MessageDialog messageDialog = new MessageDialog(
							"Xóa thành công!", childLocal);
					messageDialog.setVisible(true);

					iDatabase = "";
					CapNhapTile();
				} else {
					MessageDialog messageDialog = new MessageDialog(
							"Xóa thất bại!", childLocal);
					messageDialog.setVisible(true);
				}

			}
		});
		panel.add(btnDeleleDatabase, "11, 1");
	}

	// ////////////////////////////////////////////////////////////////////////

	boolean ktTrungDatabase(String str) {
		for (int i = 0; i < listDatabase.size(); i++) {
			if (str.equals(listDatabase.get(i).getName())) {
				return true;
			}
		}
		return false;
	}

	int count(String str, char temp) {
		int dem = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == temp) {
				dem++;
			}
		}
		return dem;
	}

	int index(String str, char temp, int n) {
		int dem = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == temp) {
				dem++;
			}
			if (dem == n) {
				return i;
			}
		}
		return -1;
	}

	public static void LoadData(String path) {

		File folder = new File(path);
		File[] dsFile = folder.listFiles();
		for (int i = 0; i < dsFile.length; i++) {
			if (dsFile[i].getName().contains(".xml")) {
				MyDatabase database;
				try {
					database = new MyDatabase(path + "/" + dsFile[i].getName());
				} catch (Exception e) {
					return;
				}
				listDatabase.add(database);
			}
		}

	}

	public static void LoadTreeView() throws TransformerException {

		jTreeDatabase.removeAll();
		// Tao node goc cua cay
		DefaultMutableTreeNode rootNode;
		DefaultTreeModel model;

		rootNode = new DefaultMutableTreeNode("database");
		model = new DefaultTreeModel(rootNode);
		jTreeDatabase.setModel(model);
		for (int k = 0; k < listDatabase.size(); k++) {
			MyDatabase database = listDatabase.get(k);
			DefaultMutableTreeNode databaseNode = new DefaultMutableTreeNode(
					database.getName());
			
			// danh sach cac tables
			ArrayList<MyTable> tables = database.getTables();
			for (int i = 0; i < tables.size(); i++) {
				MyTable iTable = tables.get(i);
				DefaultMutableTreeNode tableNode = new DefaultMutableTreeNode(
						iTable.getName());							

				// danh sach cac columns
				ArrayList<MyColumn> columns = iTable.getColumns();
				for (int j = 0; j < columns.size(); j++) {
					MyColumn iColumn = columns.get(j);
					DefaultMutableTreeNode columnNode = new DefaultMutableTreeNode(
							iColumn.getName() + " (type: "
									+ iColumn.getType() + ")");
					
					tableNode.add(columnNode);
				}
				databaseNode.add(tableNode);
			}
			rootNode.add(databaseNode);
		}
		// jTreeDatabase.expandRow(0);
		expand(new TreePath(jTreeDatabase.getModel().getRoot()));

	}

	private static void expand(TreePath path) {
		TreeNode node = (TreeNode) path.getLastPathComponent();
		if (node.getChildCount() >= 0) {
			java.util.Enumeration e = node.children();
			while (e.hasMoreElements()) {
				TreeNode n = (TreeNode) e.nextElement();
				expand(path.pathByAddingChild(n));
			}
		}
		jTreeDatabase.expandPath(path);

	}

	private void CapNhapTile() {
		if (iDatabase != "")
			setTitle("SQL server - database: " + iDatabase);
		else
			setTitle("SQL server");
	}
	
	Boolean ktLaSo(String st)
	{
		if(st.contains("1"))
			return true;
		if(st.contains("2"))
			return true;
		if(st.contains("3"))
			return true;
		if(st.contains("4"))
			return true;
		if(st.contains("5"))
			return true;
		if(st.contains("6"))
			return true;
		if(st.contains("7"))
			return true;
		if(st.contains("8"))
			return true;
		if(st.contains("9"))
			return true;
		
		if(st.contains("0"))
			return true;
		
		return false;
	}

}
